#! /usr/bin/python
import socket, sys, re, os

def normalise(data):

	ddecode = data.decode('utf-8')
	data_array = re.findall(r'[0-9a-fA-F]{2}', ddecode)
		
	return data_array
	
def print_table(col, mylist, conv):

	tables = ''

	if col == None:
		col = 8

	count = 0
	
	for x in mylist:
		
		count += 1

		if conv == 'hex':
			tables += str(x)
			tables += ' '
		elif conv == 'dec':
			num = int(x, 16)
			num = str(num).rjust(3)
			tables += num
			tables += ' '
		elif conv == 'ascii':
			num = int(x, 16)
			if num >= 20 and num <= 126:
				tables += chr(num)
			else:
				tables += '.'
					
		if count >= col and not conv == 'ascii':
			tables += '\n'
			count = 0
			
	return tables

def main(args):

	columns = 8
		
	if not (len(args) > 0):

		try:

			while True:
		
				hex = input(r'Enter hex (\x, 0x, FF FF, FFFF): ')
				
				hex_array = re.findall(r'[0-9a-fA-F]{2}', hex)

				print ('\n[+]\tHex\n')
				hex_tables = print_table(columns, hex_array, 'hex')
				print (hex_tables)
				
				print ('\n[+]\tDecimal\n')
				dec_tables = print_table(columns, hex_array, 'dec')
				print (dec_tables + '\n')
				
				print ('\n[+]\tAscii\n')
				dec_tables = print_table(columns, hex_array, 'ascii')
				print (dec_tables + '\n')
		
		except KeyboardInterrupt:
			print ('\n')
		sys.exit(0)
	
	else:
		for hex in args:

			path = os.path.normpath(hex)

			print ('\n[+]\tOpening: ' + path + '\n')

			file = open(path, 'rb')
			data = file.read()
			file.close()
				
			hex_array = normalise(data)
				
			print ('[+]\tHex\n')
			hex_tables = print_table(columns, hex_array, 'hex')
			print (hex_tables)
			
			print ('\n[+]\tDecimal\n')
			dec_tables = print_table(columns, hex_array, 'dec')
			print (dec_tables)
			
			print ('\n[+]\tAscii\n')
			ascii_tables = print_table(columns, hex_array, 'ascii')
			print (ascii_tables)
			
			f = open(str(path + '.conv.txt'), 'w+')
			f.write('[+]\tHex ---\n')
			f.write(hex_tables)
			f.write('\n')
			f.write('[+]\tDecimal ---\n')
			f.write(dec_tables)
			f.write('\n')
			f.write('[+]\tAscii ---\n')
			f.write(ascii_tables)
			f.close()
			
			print ( '\n[+]\tSaved to -> ' + path)
			
			print ('\n[+]\tConverted & saved!\n')

if __name__ == "__main__":
	args = sys.argv[1:]
	main(args)
	input('Press Enter to quit')
	sys.exit(0)
